<!--
 * @Author: yuandawei
 * @Date: 2020-11-04 17:05:59
 * @LastEditTime: 2020-11-20 16:17:57
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \vue-admin-beautiful-pro-template\src\views\index\index.vue
-->
<template>
  <div class="distribution-container">
    <div class="wrapper">
      <HHsearch
        ref="search"
        :search-options="searchOptions"
        :btn-option="2"
        @search="search"
        @reset="reset"
        @export="handleExport"
      ></HHsearch>

      <HHtable
        ref="table"
        :border="true"
        :total="total"
        :table-data="tableData"
        :table-column="tableColumn"
        :btn-option="btnOption"
        @page-click="pageClick"
      >
        <!-- 累计积分 -->
        <template #allbalanceSlot="{ data }">
          <div class="remark-edit flex-center">
            <span v-if="data.isBalanceShow">{{ data.allbalance || '无' }}</span>
            <el-tooltip v-else :content="value4" placement="top" effect="light">
              <el-input v-model="value4" placeholder="请输入内容"></el-input>
            </el-tooltip>
            <img
              v-if="data.isBalanceShow"
              src="@/assets/imgs/edit.png"
              alt=""
              style="margin-left: 10px"
              @click="editBalance(data)"
            />
            <img
              v-else
              src="@/assets/imgs/save.png"
              alt=""
              @click="saveBalance(data)"
            />
          </div>
        </template>
        <!-- 备注 -->
        <template #remarkSlot="{ data }">
          <div class="remark-edit flex-center">
            <span v-if="data.isShow">{{ data.remark || '无' }}</span>
            <el-tooltip v-else :content="value3" placement="top" effect="light">
              <el-input v-model="value3" placeholder="请输入内容"></el-input>
            </el-tooltip>
            <img
              v-if="data.isShow"
              src="@/assets/imgs/edit.png"
              alt=""
              style="margin-left: 10px"
              @click="editRemark(data)"
            />
            <img
              v-else
              src="@/assets/imgs/save.png"
              alt=""
              @click="saveRemark(data)"
            />
          </div>
        </template>
      </HHtable>
    </div>
    <modal
      title="冻结分销确认"
      :show-modal="showFreezeModal"
      @confirm="confirmFreeze(0)"
      @cancel="showFreezeModal = false"
    >
      <template #body>
        <div class="container">
          <div class="title">
            <div class="icon el-icon-warning"></div>
            <div class="message">确定冻结所选分销员的分销关系吗？</div>
          </div>
          <div class="bottom">
            <p>说明：</p>
            <p>1、客户下单后订单归属机构，分销员不再分佣；</p>
            <p>2、被冻结期间，通过链接、二维码等途径新增的客户，均归机构所有</p>
            <p>3、被冻结前的客户关系保持不变，解冻后恢复正常；</p>
            <p>4、冻结期间，招生顾问的累计积分和相关订单金额不会自动变更。</p>
          </div>
        </div>
      </template>
    </modal>
    <modal
      title="解冻分销确认"
      :show-modal="showUnfreezeModal"
      @confirm="confirmFreeze(1)"
      @cancel="showUnfreezeModal = false"
    >
      <template #body>
        <div class="container">
          <div class="title">
            <div class="icon el-icon-warning"></div>
            <div class="message">确定解冻所选分销员的分销关系吗？</div>
          </div>
          <div class="bottom">
            <p>说明：</p>
            <p>1、解冻分销后，原客户关系恢复正常；</p>
          </div>
        </div>
      </template>
    </modal>
    <el-dialog
      :visible.sync="dialogVisible"
      width="40%"
      title="修改关系"
      :lock-scroll="false"
    >
      <el-row>
        <el-col :span="24">
          <el-radio-group
            v-model="radio"
            style="margin-right: 30px"
            @change="radioChange"
          >
            <el-radio-button :label="0">未绑定</el-radio-button>
            <el-radio-button :label="1">已绑定</el-radio-button>
          </el-radio-group>
          <el-radio-group v-model="upDown" @change="radioChange2">
            <el-radio-button :label="2">上级</el-radio-button>
            <el-radio-button :label="1">下级</el-radio-button>
          </el-radio-group>
        </el-col>
        <el-col
          v-if="radio !== null && upDown !== null"
          :span="16"
          style="display: flex; float: right; margin-top: 20px"
        >
          <el-input
            v-model="searchForm.userName"
            clearable
            size="small"
            placeholder="输入名称搜索"
            prefix-icon="el-icon-search"
            style="margin-right: 10px"
          ></el-input>
          <el-input
            v-model="searchForm.cellphone"
            clearable
            size="small"
            placeholder="输入电话搜索"
            prefix-icon="el-icon-search"
            style="margin-right: 10px"
          ></el-input>
          <el-button type="primary" @click="dialogSearch">搜索</el-button>
        </el-col>
      </el-row>
      <HHtable
        v-if="radio !== null && upDown !== null"
        :border="true"
        :height="400"
        :total="total2"
        :check-box="true"
        :table-data="tableData2"
        :table-column="tableColumn2"
        @page-click="pageClick2"
        @selection-change="handleSelection"
      ></HHtable>
      <div class="dialog-bottom flex flex-center">
        <el-button type="primary" @click="confirm">{{ name }}</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import HHsearch from '@/components/HH-search'
  import HHtable from '@/components/HH-table'
  import Modal from '@/components/HH-modal'
  import { splicingUrl } from '@/utils/validate'
  import {
    getDistributorList,
    // exportDistributor,
    getDistributorUpDown,
    unbindSuperior,
    bindSuperior,
    editDistributorRemark,
    editDistributorPoints,
  } from '@/api/distribution'
  // import { getUnfreezeCounselor } from '@/api/conunselor'
  import { freezeDistributor } from '@/api/common'
  export default {
    name: 'Index',
    components: {
      HHsearch,
      HHtable,
      Modal,
    },
    data() {
      return {
        showFreezeModal: false,
        showUnfreezeModal: false,
        dialogVisible: false,
        radio: null,
        upDown: null,
        value3: '',
        value4: '',
        searchForm: {
          cellphone: '',
          userName: '',
        },
        total: 0,
        total2: 0,
        searchOptions: [
          {
            type: 'select',
            prop: 'status',
            label: '状态：',
            span: 5,
            placeholder: '请选择',
            arr: [
              {
                value: '',
                label: '全部招生顾问',
              },
              {
                value: 1,
                label: '正常分销',
              },
              {
                value: 0,
                label: '冻结分销',
              },
            ],
          },
          {
            type: 'text',
            prop: 'userName',
            span: 6,
            label: '分销员名称：',
            placeholder: '选择或输入搜索',
          },
          {
            type: 'text',
            prop: 'cellphone',
            label: '手机号：',
            span: 5,
            placeholder: '选择或输入搜索',
          },
          {
            type: 'daterange',
            prop: 'daterange',
            label: '成为分销员日期：',
            span: 8,
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期',
            valueFormat: 'yyyy-MM-dd',
          },
        ],
        tableColumn: [
          {
            prop: 'username',
            label: '分销员名称',
          },
          {
            prop: 'cellphone',
            label: '手机号码',
          },
          {
            prop: 'spoorer',
            label: '所属招生顾问',
          },
          {
            prop: 'inviteuser',
            label: '邀请人(上一级）',
            width: 150,
          },
          {
            prop: 'lowercount',
            label: '下一级人数',
          },
          {
            prop: 'createdate',
            label: '成为分销员时间',
            width: 150,
          },
          {
            prop: 'statusVal',
            label: '分销状态',
          },
          {
            prop: 'allbalance',
            label: '累计积分',
            slotContent: 'allbalanceSlot',
          },
          {
            prop: 'orderMoney',
            width: 150,
            label: '相关订单金额（元）',
          },
          {
            prop: 'remark',
            label: '备注',
            width: 150,
            slotContent: 'remarkSlot',
          },
        ],
        tableData: [],
        btnOption: [
          {
            type: 'primary',
            size: 'mini',
            text: '查看信息',
            except: 2,
            show: true,
            func: this.edit,
          },
          {
            type: 'info',
            size: 'mini',
            text: '冻结分销',
            except: 0,
            show: true,
            func: this.handleFreeze,
          },
          {
            type: 'warning',
            size: 'mini',
            text: '解冻分销',
            except: 1,
            show: true,
            func: this.handleUnfreeze,
          },
          {
            type: 'danger',
            size: 'mini',
            text: '修改关系',
            except: 2,
            show: true,
            func: this.handleChangeRelation,
          },
        ],
        dialogColumn: [],
        dialogData: [],
        params: {
          pageSize: 10,
          pageNumber: 1,
          status: '',
          userName: '',
          cellphone: '',
          inviteUser: '',
          startTime: '',
          endTime: '',
        },
        params2: {
          pageSize: 10,
          pageNumber: 1,
          type: 0,
          id: 0,
        },
        params3: {
          pageSize: 10,
          pageNumber: 1,
          status: '',
          userName: '',
          cellphone: '',
          inviteUser: '',
          startTime: '',
          endTime: '',
        },
        tableColumn2: [
          {
            prop: 'username',
            label: '分销员名称',
          },
          {
            prop: 'cellphone',
            label: '手机号码',
          },
        ],
        tableData2: [],
        distributorInfo: {}, //当前操作分销员的信息
        selectionArray: [], // 选择操作人的数组
        user: JSON.parse(localStorage.getItem('user')) || '',
      }
    },
    computed: {
      name() {
        if (this.radio == 1) {
          return '解除绑定'
        } else {
          return '绑定关系'
        }
      },
    },
    mounted() {
      const user = JSON.parse(localStorage.getItem('user'))
      const route = [
        'S22',
        'S52',
        '1368',
        'S68',
        'T14',
        'T59',
        'S30',
        'S71',
        '360',
        '446',
        '1330',
        '245',
        '635',
      ]
      if (!route.includes(user.username)) {
        this.btnOption = [
          {
            type: 'primary',
            size: 'mini',
            text: '查看信息',
            except: 2,
            show: true,
            func: this.edit,
          },
        ]
      }
      this.init()
    },
    methods: {
      init() {
        this.getList()
      },
      radioChange() {
        this.params2.pageNumber = 1
        this.getDistributorUpDown()
      },
      radioChange2() {
        this.params3.pageNumber = 1
        this.getDistributorUpDown()
      },
      getList() {
        this.$refs.table.loading = true
        this.params.spoorerid = JSON.parse(
          localStorage.getItem('user')
        ).oprationId
        getDistributorList(this.params).then((res) => {
          const arr = res.data.list
          arr.forEach((item) => {
            if (item.imgUrl) item.imgUrl = imageUrl(item.imgUrl)
            if (item.wxCode) item.wxCode = imageUrl(item.wxCode)
            item.isShow = true
            item.isBalanceShow = true
          })
          this.tableData = arr
          this.total = res.data.total
          setTimeout(() => {
            this.$refs.table.loading = false
          }, 1000)
        })
      },
      editBalance(data) {
        this.tableData.map((item) => {
          item.isBalanceShow = true
        })
        data.isBalanceShow = false
        this.value4 = data.allbalance.toString()
      },
      saveBalance(data) {
        data.isBalanceShow = true
        const params = {
          distributorId: data.id,
          points: this.value4,
        }
        editDistributorPoints(params)
          .then((res) => {
            if (res.code === 200) {
              this.$baseMessage('修改成功', 'success')
              this.value4 = ''
              this.getList()
            } else {
              this.$baseMessage(res.msg, 'error')
            }
          })
          .catch((error) => {
            this.value4 = ''
          })
      },
      editRemark(data) {
        this.tableData.map((item) => {
          item.isShow = true
        })
        data.isShow = false
        this.value3 = data.remark
      },
      saveRemark(data) {
        data.isShow = true
        const params = {
          id: data.id,
          remark: this.value3,
        }
        editDistributorRemark(params)
          .then((res) => {
            if (res.code === 200) {
              this.$baseMessage('修改成功', 'success')
              this.value3 = ''
              this.getList()
            } else {
              this.$baseMessage(res.msg, 'error')
            }
          })
          .catch((error) => {
            this.value3 = ''
          })
      },
      edit(res) {
        this.$router.push({
          path: `/detail/${res.id}`,
          query: { identity: 1 },
        })
      },
      handleFreeze(res) {
        this.showFreezeModal = true
        this.distributorInfo = res
      },
      handleUnfreeze(res) {
        this.showUnfreezeModal = true
        this.distributorInfo = res
      },
      confirmFreeze(status) {
        let params = {
          status,
          ids: this.distributorInfo.id.toString(),
        }
        freezeDistributor(params).then((res) => {
          if (res.code === 200) {
            this.init()
            this.showFreezeModal = false
            this.showUnfreezeModal = false
            let msg = '冻结成功'
            if (status === 1) msg = '解冻成功'
            this.$baseMessage(msg, 'success')
          } else {
            this.$baseMessage(res.msg, 'error')
          }
        })
      },
      search(res) {
        if (res.daterange) {
          res.startTime = res.daterange[0]
          res.endTime = res.daterange[1]
          delete res.daterange
        }
        const arr = Object.keys(res)
        for (let i = 0; i < arr.length; i++) {
          this.params[arr[i]] = res[arr[i]]
        }
        this.init()
      },
      reset() {
        this.params = {
          pageSize: 10,
          pageNumber: 1,
          status: '',
          userName: '',
          cellphone: '',
          inviteUser: '',
          startTime: '',
          endTime: '',
        }
        this.$refs.search.removeFilterArray()
        this.init()
      },
      handleExport(res) {
        if (res.daterange) {
          res.startTime = res.daterange[0]
          res.endTime = res.daterange[1]
          delete res.daterange
        }
        let url = splicingUrl(res)
        const link = document.createElement('a')
        link.style.display = 'none'
        link.href = this.baseURL + '/distributor/exportDistributor.do?' + url
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
      },
      handleChangeRelation(res) {
        this.dialogVisible = true
        this.radio = null
        this.upDown = null
        this.distributorInfo = res
      },
      dialogSearch() {
        // 绑定的搜索
        if (this.radio == 0) {
          this.params3.userName = this.searchForm.userName
          this.params3.cellphone = this.searchForm.cellphone
          this.bindSearch()
        } else {
          // 解绑的搜索
          this.params2.userName = this.searchForm.userName
          this.params2.cellphone = this.searchForm.cellphone
          this.unbindSearch()
        }
      },
      handleSelection(val) {
        this.selectionArray = val
      },
      bindSearch() {
        this.params2.id = this.distributorInfo.id
        this.params2.type = 2
        // 查看有没有分销员上级
        getDistributorUpDown(this.params2).then((res) => {
          if (res.data.total == 1) {
            // 有上级的时候排除上级
            this.params3.upid = [
              res.data.list[0].id,
              this.distributorInfo.id,
            ].join(',')
          } else {
            // 没有上级的时候要排除自己
            this.params3.upid = this.distributorInfo.id
          }
          if (this.upDown == 1) {
            // 查找绑定下级查询
            this.params3.notupid = 1
            getDistributorList(this.params3).then((res) => {
              if (res.code == 200) {
                this.tableData2 = res.data.list
                this.total2 = res.data.total
              }
            })
          } else {
            this.params3.notupid = ''
            getDistributorList(this.params3).then((res) => {
              if (res.code == 200) {
                this.tableData2 = res.data.list
                this.total2 = res.data.total
              }
            })
          }
        })
      },
      unbindSearch() {
        this.params2.id = this.distributorInfo.id
        this.params2.type = this.upDown
        getDistributorUpDown(this.params2).then((res) => {
          if (res.code === 200) {
            this.tableData2 = res.data.list
            this.total2 = res.data.total
          }
        })
      },
      getDistributorUpDown() {
        if (!this.upDown) return
        if (this.radio == 0) {
          //这是绑定查询
          this.bindSearch()
        } else {
          //这是解绑查询
          this.unbindSearch()
        }
      },
      pageClick(pager) {
        this.params.pageNumber = pager
        this.init()
      },
      pageClick2(pager) {
        if (this.radio == 0) {
          this.params3.pageNumber = pager
        } else {
          this.params2.pageNumber = pager
        }
        this.getDistributorUpDown()
      },
      confirm() {
        if (this.selectionArray.length < 1) {
          this.$baseMessage('请选择操作对象', 'warning')
          return
        }
        // let params
        if (this.radio == 0) {
          // 这是绑定操作
          let params = {}
          // 绑定下级
          if (this.upDown == 1) {
            const arr = []
            this.selectionArray.forEach((item) => {
              arr.push(item.id)
            })
            params.type = 2
            params.ids = arr.join(',')
          } else {
            // 绑定上级
            if (this.selectionArray.length > 1) {
              this.$baseMessage('绑定上级只能选择一个', 'warning')
              return
            }
            params.type = 4
            params.ids = this.selectionArray[0].id
          }
          params.myId = this.distributorInfo.id
          params.userName = this.distributorInfo.username
          params.oprationId = this.user.oprationId
          params.oprationName = this.user.name
          bindSuperior(params).then((res) => {
            if (res.code == 200) {
              this.$baseMessage(res.msg, 'success')
              this.getDistributorUpDown()
            } else {
              this.$baseMessage(res.msg, 'error')
            }
          })
        } else {
          // 这是解绑操作
          let params = {}
          // 解绑上级是4，解绑下级是2
          if (this.upDown == 1) {
            const arr = []
            this.selectionArray.forEach((item) => {
              arr.push(item.id)
            })
            params.type = 2
            params.ids = arr.join(',')
          } else {
            params.type = 4
            params.ids = ''
          }
          params.myId = this.distributorInfo.id
          params.userName = this.distributorInfo.username
          params.oprationId = this.user.oprationId
          params.oprationName = this.user.name
          unbindSuperior(params).then((res) => {
            if (res.code == 200) {
              this.$baseMessage(res.msg, 'success')
              this.getDistributorUpDown()
            }
          })
        }
      },
    },
  }
</script>
<style lang="scss" scoped>
  @import './../../assets/styles/common.css';
  .imgs {
    width: 100px;
    height: 100px;
    object-fit: contain;
  }
  .container {
    display: flex;
    flex-direction: column;
    .title {
      display: flex;
      align-items: center;
      justify-content: center;
      margin-bottom: 20px;
      color: #666666;
      .icon {
        margin-right: 10px;
        font-size: 24px;
        color: red;
      }
    }
    .bottom {
      padding-bottom: 20px;
      margin-left: 100px;
      font-size: 14px;
      color: #666666;
      p {
        margin: 5px;
      }
    }
  }
  .dialog-bottom {
    margin-top: 30px;
  }
  ::v-deep {
    .el-dialog__wrapper {
      overflow: hidden;
    }
    .remark-edit {
      flex-direction: column;
      .el-input__inner {
        border: none;
      }
      img {
        margin-left: auto;
        vertical-align: middle;
      }
    }
  }
  * {
    touch-action: pan-x;
  }
</style>
